<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import CustomNavbar from './components/CustomNavbar.vue'
import {
  getHomeBannerAPI,
  getHomeCategoryAPI,
  getHomeGuessLikeAPI,
  getHomeHotAPI,
} from '@/services/home'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, GuessLikeItem, HotItem } from '@/types/home'
import categoryPanel from './components/categoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './components/PageSkeleton'

const homeBannerData = ref<BannerItem[]>([])
// 获取首页轮播图数据
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  homeBannerData.value = res.result
}

const homeCategoryData = ref<CategoryItem[]>([])
// 获取前台分类数据
const getHomeCategoryData = async () => {
  // TODO: 获取分类数据
  const res = await getHomeCategoryAPI()
  homeCategoryData.value = res.result
}

const homeHotData = ref<HotItem[]>([])
// 获取热门推荐数据
const getHomeHotData = async () => {
  // TODO: 获取热门推荐数据
  const res = await getHomeHotAPI()
  homeHotData.value = res.result
}

// 是否加载中的标记
const isLoading = ref(false)

// 页面加载时执行
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

// 获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()

//滚动触底
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置猜你喜欢数据
  guessRef.value?.resetData()
  // 加载数据
  // 如果不用await直接调接口，会导致数据加载顺序不确定。如果三个接口都加上await,则会等待第一个接口返回后再执行第二个接口，以此类推，延长了数据加载时间。
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotData()
  // 这里用Promise.all()方法同时加载三个接口，这样可以保证三个接口都返回后再执行下一步操作。
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else
      ><XtxSwiper :list="homeBannerData"></XtxSwiper>
      <categoryPanel :list="homeCategoryData" />
      <HotPanel :list="homeHotData" />
      <XtxGuess ref="guessRef"></XtxGuess
    ></template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  display: flex;
  height: 100%;
  flex-direction: column;
  .scroll-view {
    flex: 1;
  }
}
</style>
